// cart.js
const cartList = document.getElementById('cart-list');
const totalPriceElement = document.getElementById('total-price');

function renderCart() {
    let cart = JSON.parse(localStorage.getItem('cart')) || [];
    cartList.innerHTML = '';
    let totalPrice = 0;
    cart.forEach((product, index) => {
        const listItem = document.createElement('li');
        listItem.innerHTML = `
            <span>${product.name}</span>
            <span>单价：¥${product.price}</span>
            <span>数量：
                <a href="javascript:;" class="reduce" data-index="${index}">-</a>
                <input type="text" value="${product.amount}">
                <a href="javascript:;" class="add" data-index="${index}">+</a>
            </span>
            <span>小计：¥${product.price * product.amount}</span>
            <a href="javascript:;" class="delete" data-index="${index}">删除</a>
        `;
        cartList.appendChild(listItem);
        totalPrice += product.price * product.amount;
    });
    totalPriceElement.textContent = totalPrice;
}

renderCart();

cartList.addEventListener('click', function(event) {
    if (event.target.classList.contains('add')) {
        const index = parseInt(event.target.dataset.index);
        let cart = JSON.parse(localStorage.getItem('cart')) || [];
        cart[index].amount++;
        localStorage.setItem('cart', JSON.stringify(cart));
        renderCart();
    } else if (event.target.classList.contains('reduce')) {
        const index = parseInt(event.target.dataset.index);
        let cart = JSON.parse(localStorage.getItem('cart')) || [];
        if (cart[index].amount > 1) {
            cart[index].amount--;
        }
        localStorage.setItem('cart', JSON.stringify(cart));
        renderCart();
    } else if (event.target.classList.contains('delete')) {
        const index = parseInt(event.target.dataset.index);
        let cart = JSON.parse(localStorage.getItem('cart')) || [];
        cart.splice(index, 1);
        localStorage.setItem('cart', JSON.stringify(cart));
        renderCart();
    }
});